package scrumtaculous.web;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletActionRedirectResult;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import scrumtaculous.domain.Story;
import scrumtaculous.service.StoryManager;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Validateable;
import com.opensymphony.xwork2.ValidationAwareSupport;

@Results(
{
   @Result(name = "success", type = ServletActionRedirectResult.class, value = "stories")
})
public class StoriesController extends ValidationAwareSupport implements ModelDriven<Object>, Validateable
{

   Resource resource = new ClassPathResource("web-spring-beans.xml");
   BeanFactory factory = new XmlBeanFactory(resource);

   private StoryManager storyManager = (StoryManager) factory.getBean("StoryManager");
   private Integer id;
   private Story model;
   private List<Story> list;

   protected Log log;

   public StoriesController()
   {
      log = LogFactory.getLog(StoriesController.class);
   }

   // Handles /stories/{id} GET requests
   public HttpHeaders show()
   {
      // If id is 0, serialize all values (for now)
      log.debug("looking for " + id);
      if (id == 0)
      {
         list = storyManager.find();
      }
      else
      {
         list = null;
         model = storyManager.find(id);
      }
      return new DefaultHttpHeaders("show");
   }

   // GET /stories
   public HttpHeaders index()
   {
      list = storyManager.find();
      return new DefaultHttpHeaders("index").disableCaching();
   }

   public void validate()
   {
      if (model.getIterationId() == null)
      {
         addFieldError("clientName", "The client name is empty");
      }
   }

   public Object getModel()
   {
      return (list != null ? list : model);
   }

   public void setId(Integer idIn)
   {
      id = idIn;
   }

   ////////////////////////////////
   // Spring DI
   ////////////////////////////////
   public void setStoryManager(StoryManager storyManagerIn)
   {
      storyManager = storyManagerIn;
   }

}
